

 
 
var av = {

    avs: [],
    dirPath: null,
    page: null,
    ui: {
        width: parseInt(config['av.img.width'])
    },
    sort: {
        type: "name",// name，imgWidth，videSize
        fx: "asc"// asc，desc
    },
    load: function (path) {

        // 赋予路径
        if (path) {
            this.dirPath = path;
        } else {
            this.dirPath = config["av.default.path"];
        }
        this.dirPath = new PFile(this.dirPath).path;
        console.log("avDirPath：" + this.dirPath);

        // 加载文件
        this.avs = [];
        this.createAvDir(this.dirPath);
        this.sortAv();

        // 分页
        this.page = new PPage(this.avs.length, parseInt(config['av.pageSize']));
    },
    createHtml: function () {
        var that = this;

        // 清空
        $("#avsContainer").html("");

        this.createTools();
        // 页数从1开始，所以要减一
        for (var i = this.page.getStart() - 1; i <= this.page.getEnd() - 1; i++) {
            var av = this.avs[i];
            this._createRow(av, i);
        }
        this.addScrollStop();
        this.setLength();
        $(window).scrollTop(0);
    },

    // 创建单个的
    _createRow: function (av, i) {
        var that = this;
        var isOk = (av.video ? true : false);
        var hasOther = av.other ? true : false;
        var hasImg = av.img ? true : false;
        var hasVideo = av.video ? true : false;
        var isOnlyOther = hasOther && !hasImg && !hasVideo;

        // div
        var div = $("<div av='container' class='avContainer' ></div>");

        if (config["av.showOther"] != "true" && !isOnlyOther) {
            div.appendTo($("#avsContainer"))
        }

        var titleMsg = "";
        if (isOk) {
            var size = av.video.sizeInfo;
            titleMsg = "目录：" + av.dirPath + "\n\n视频：" + av.video.path + "（" + size + "）";
        } else {
            titleMsg = "目录：" + av.dirPath;
        }

        div.attr("title", titleMsg);
        if (isOk) {
            div.addClass("bg-dark");
        } else {
            div.addClass("bg-steel");
        }

        // num
        var num = i;
        var n = $("<button av='number' class='avNumber button large success'></button>").html(num).appendTo(div);
        n.click(function () {
            nw.Shell.openItem(av.dirPath);
        });

        // 有图片
        if (av.img) {
            var imgHtml = $("<img av='img' class='avPic' src='" + av.img.path + "'></img>");
            imgHtml.one("load", function () {
                av.img.realWidth = $(this).width();
                if ($(this).width() > that.ui.width) {
                    $(this).width(that.ui.width);
                }
            });
            if (isOk) {
                imgHtml.click(function () {
                    nw.Shell.openItem(av.video.path);
                });
                imgHtml.css("cursor", "pointer");

            }
            div.append(imgHtml);
        }
        // 无图片，有视频
        if (!av.img && av.video   ) {
          
                var videoBtn = $("<button av='video' class='avFileButton button large'></button>")
                    .html(av.video.path);
                videoBtn.click(function () {
                    nw.Shell.openItem(av.video.path);
                });
                div.append(videoBtn);
             
        }

        // other button
        if (av.other) {
            var otherBtn = $("<button av='other' class='avFileButton button large'></button>").html(av.other.fileName);
            otherBtn.click(function () {
                nw.Shell.openItem(av.other.path);
            });
            div.append(otherBtn);
        }

    },


    createAvDir: function (dirPath) {
        var fileNames = new PFile(dirPath).getAllSon();
        console.log(fileNames);
        for (var i = 0; i < fileNames.length; i++) {
            this.createAv(fileNames[i]);
        }
    },
    createAv: function (filePath) {
        var file = new PFile(filePath);
        console.log(filePath);
        if (file.isDir) {
            this.createAvDir(file.path);
            return;
        }

        if (fileUtils.isRemove(file.path)) {
            return;
        }

        var av = this._getAv(file.dirPath, file.fileName, file.baseName);
        if (av == null) {
            av = {
                dirPath: file.dirPath,
                baseName: file.baseName
            };
            this.avs.push(av);
        }

        if (fileUtils.isImg(filePath)) {
            av.img = file;
        } else if (fileUtils.isVideo(filePath)) {
            av.video = file;
        } else {
            av.other = file;
        }

    },

    _getAv: function (dirPath, fileName, baseName) {
        for (var i = 0; i < this.avs.length; i++) {
            var av = this.avs[i];
            if (av.baseName == baseName && av.dirPath == dirPath) {
                return av;
            }
        }
        return null;
    },

    addScrollStop: function () {

    },

    setLength: function () {
        $("button[av='video']").each(function () {
            var fileName = $(this).text();
            var f = new PFile(fileName);
            var msg=f.fileName;
            if (msg.length > 40) {
                msg= f.baseName.substring(0, 40) + "...." + f.extName;                
            } 
            $(this).text(msg);
        });
        $("button[av='other']").each(function () {
            var fileName = $(this).text();
            var f = new PFile(fileName);
            var msg=f.fileName;
            if (msg.length > 40) {
                msg= f.baseName.substring(0, 40) + "...." + f.extName;                
            } 
            $(this).text(msg);
        });
    },

    createTools: function () {
        var that = this;
        // 创建button
        var tools = $("<div class='avTools bg-dark span13'></div>").appendTo($("#avsContainer"));

        var dirDiv = $('<button class="avNumber button large warning">首页</button>').appendTo(tools);
        dirDiv.click(function() {
         window.location.href="/index.html";
        });

        // 选择文件夹
        var fileChooseButton = $('<button class="avNumber button success large">选择文件夹</button>').appendTo(tools);
        dirChooser(fileChooseButton, function (dirPath) {
            if (!dirPath) {
                return;
            }
            if (dirPath.lastIndexOf("/") != dirPath.length - 1) {
                dirPath += "/";
            }
            if (this.dirPath != dirPath) {
                that.load(dirPath);
                that.createHtml();
            }

        });

       

        // 排序
        var sort = $('<button id="sortButton" class="avNumber button large span2"></button>').html("排序").appendTo(tools);
        sort.click(function () {
            if (that.sort.fx == "asc") {
                that.sort.fx = "desc";
            } else {
                that.sort.fx = "asc";
            }
            that.sortAv();
            that.createHtml();
        });

        $("#sortPopDiv").html("");
        $("#sortPopDiv").load("sort.html", function () {
             uiUtils.addMouseShow("sortButton", "sortPopDiv", 0, -5, "avsContainer");
            $("#sortPopDiv").find("input").each(function () {
                var btn = $(this);
                addMouseClass(btn, "warning");
                if (btn.attr("sFx") == that.sort.fx && btn.attr("sType") == that.sort.type) {
                    btn.removeClass("success");
                    $("#sortButton").html(btn.val());
                }
                btn.click(function () {
                    that.sort.fx = $(this).attr("sFx");
                    that.sort.type = $(this).attr("sType");
                    that.sortAv();
                    that.createHtml();
                });
            });

        });

        // 放大
        var zoom = $('<button id="zoomButton" class="avNumber button large span2"></button>').html("缩放"
            + "&nbsp;&nbsp;&nbsp;&nbsp;" + that.ui.width).appendTo(tools);
        zoom.click(function () {
            var res = that.ui.width + 100;
            if (res > 1000) {
                res = 100;
            }
            that.ui.width = res;
            that.createHtml();
        });
        $("#zoomPopDiv").html("");

        $("#zoomPopDiv").load("zoom.html", function () {
            uiUtils.addMouseShow("zoomButton", "zoomPopDiv", 0, -5, "avsContainer");
            $("#zoomPopDiv").find("input").each(function () {
                addMouseClass($(this), "warning");
                if ($(this).val() == that.ui.width) {
                    $(this).removeClass("success");
                }
                $(this).click(function () {
                    that.ui.width = parseInt($(this).val());
                    that.createHtml();
                });
            });
        });
        // 前一页
        var prePage = $('<button class="avNumber button large"></button>').html("上一页").appendTo(tools);
        prePage.click(function () {
            var i = that.page.curPage - 1;
            i = i < 1 ? 1 : i;
            that.page.forwardPage(i);
            that.createHtml();
            $(window).scrollTop(0);
        });

        // 下一页
        var netPage = $('<button class="avNumber button large"></button>').html("下一页").appendTo(tools);
        netPage.click(function () {
            var i = that.page.curPage + 1;
            i = i > that.page.pageCount ? that.page.pageCount : i;
            that.page.forwardPage(i);
            that.createHtml();
            $(window).scrollTop(0);
        });

        // 分页
        $("#pagePopDiv").html("");
        var pageMsg = that.page.curPage + "/" + that.page.pageCount;
        var itemMsg = that.page.getStart() + "~" + that.page.getEnd() + "/" + that.page.itemCount;
        var msg = pageMsg + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + itemMsg;
        var infoPage = $('<button id="pageInfo" class="avNumber button large success span3"></button>').html(msg)
            .appendTo(tools);
        var page = that.page;
        var pages = page.getPageCount(10);
        for (var i = 0; i < pages.length; i++) {
            var p = pages[i];
            var pInfo = page.getPageInfo(p);
            var sg1 = p + "";
            var sg2 = pInfo.start + "~" + pInfo.end;
            var sg3 = "";
            for (var k = 0; k < 30 - sg1.length - sg2.length; k++) {
                sg3 += " ";
            }

        
            var sg = sg1 + sg3 + sg2;
            var b = $('<input  type="button" class="success large"/>').appendTo($("#pagePopDiv"));
            $("<hr style='margin:0px;height:1px;'>").appendTo($("#pagePopDiv"));
           
            b.val(sg);
            if (p == page.curPage) {
                b.removeClass("success");
            }
            addMouseClass(b, "warning");
            (function (n) {
                b.click(function () {
                    that.page.forwardPage(n);
                    that.createHtml();
                    $(window).scrollTop(0);
                    // 触发一次修改弹出窗口位置
                });
            })(p);

        }
          uiUtils.addMouseShow("pageInfo", "pagePopDiv", 0, -5, "avsContainer");

        // 加样式
        tools.find("button").addClass("success").addClass("button");
        var i = that.page.curPage;
        if (i >= that.page.pageCount) {
            netPage.attr("disabled", true);
            netPage.removeClass("success").addClass("bg-gray");
        }
        if (i <= 1) {
            prePage.attr("disabled", true);
            prePage.removeClass("success").addClass("bg-gray");
        }

    },
    sortAv: function (fx, type) {
        var so = this.sort;
        if (fx) {
            so.fx = fx;
        }
        if (type) {
            so.type = type;
        }
        type = so.type;
        fx = so.fx;

        if (type == "name") {
            this._sortByName();
        }
        if (type == "imgWidth") {
            this._sortByImgWidth();
        }
        if (type == "videSize") {
            this._sortByVideSize();
        }

    },
    _sortByName: function () {
        this.avs.sort(function (a, b) {
            var an = "";
            var bn = "";
            an = a.dirPath + a.baseName;
            bn = b.dirPath + b.baseName;
            if (an == null && bn != null) {
                return -1;
            } else if (an != null && bn == null) {
                return 1;
            } else if (an == bn) {
                return 0;
            } else {
                return an > bn ? 1 : -1;
            }
        });
        if (this.sort.fx == "desc") {
            this.avs.reverse();
        }
    },
    _sortByImgWidth: function () {
        this.avs.sort(function (a, b) {
            var aw = 0;
            var bw = 0;
            aw = a.img == null ? 0 : a.img.realWidth;
            bw = b.img == null ? 0 : b.img.realWidth;
            log(aw + ":" + bw);
            if (aw == bw) {
                return 0;
            } else {
                return (aw - bw) > 0 ? 1 : -1;
            }
        });
        var fx = this.sort.fx;
        if (this.sort.fx == "desc") {
            this.avs.reverse();
        }
    },
    _sortByVideSize: function () {
        this.avs.sort(function (a, b) {
            var aSize = 0;
            var bSize = 0;
            aSize = a.video == null ? 0 : a.video.fileSize;
            bSize = b.video == null ? 0 : b.video.fileSize;
            if (aSize == bSize) {
                return 0;
            } else {
                return (aSize - bSize) > 0 ? 1 : -1;
            }
        });
        var fx = this.sort.fx;
        if (this.sort.fx == "desc") {
            this.avs.reverse();
        }
    }
};
